//
//  TKIMHelper.m
//  TKIM
//
//  Created by liupm on 15/10/29.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMHelper.h"
#import "TKIMImageBrowserView.h"
#import "UIImage+GIF.h"
@implementation TKIMHelper


/**
 *  @Author lpm, 15-10-29 11:10:06
 *
 *  @brief  获得通讯录朋友列表分组
 *
 *  @return
 */
+ (TKIMSettingGroup *) getFriensListItemsGroup
{
    TKIMSettingItem *notify = [[TKIMSettingItem alloc] initWithTitle:@"申请与通知" cssClass:@".IMIconRequest"];
    TKIMSettingItem *chatRoom = [[TKIMSettingItem alloc] initWithTitle:@"聊天室列表" cssClass:@".IMIconRoom"];
    TKIMSettingItem *offical = [[TKIMSettingItem alloc] initWithTitle:@"公众号" cssClass:@".IMIconGroup"];
    TKIMSettingItem *room = [[TKIMSettingItem alloc] initWithTitle:@"群组" cssClass:@".IMIconGroup"];
    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:notify,chatRoom,offical,room, nil];
//    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems: nil];

    return group;
}


/**
 *  @Author lpm, 15-10-29 11:10:06
 *
 *  @brief  获得通讯录朋友列表分组
 *
 *  @return
 */
+ (TKIMSettingGroup *) getFriensAddItems
{
    TKIMSettingItem *conact = [[TKIMSettingItem alloc] initWithTitle:@"手机联系人" cssClass:@".IMIconContact"];
    TKIMSettingItem *scan = [[TKIMSettingItem alloc] initWithTitle:@"扫一扫" cssClass:@".IMIconQrcode0"];
    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:conact,scan,nil];
    
    return group;
}

/**
 *  @Author lpm, 15-10-29 11:10:06
 *
 *  @brief  获得设置列表分组
 *
 *  @return
 */
+ (NSMutableArray *) getSetGroups
{
    NSMutableArray *groups = [NSMutableArray array];
    TKIMSettingItem *autoLogin = [[TKIMSettingItem alloc] initWithTitle:@"自动登录"  type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *clearConv = [[TKIMSettingItem alloc] initWithTitle:@"清空会话"];
    TKIMSettingItem *push = [[TKIMSettingItem alloc] initWithTitle:@"消息通知"];
    TKIMSettingItem *changeSkin = [[TKIMSettingItem alloc] initWithTitle:@"切换皮肤"];

    TKIMSettingGroup *group1 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:autoLogin, clearConv,push,changeSkin, nil];
    NSString *l = [NSString stringWithFormat:@"退出登录[%@]",[TKIMSDKHelper getLoginUserName]];
    
    TKIMSettingItem *loginOut = [[TKIMSettingItem alloc] initWithTitle:l type:TKIMSettingItemTypeButton];
    TKIMSettingGroup *group2 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:loginOut, nil];
    
    TKIMSettingItem *accountInfo = [[TKIMSettingItem alloc] initWithTitle:@"个人信息" ];
    TKIMSettingGroup *group3 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:accountInfo, nil];
    
    TKIMSettingItem *version = [[TKIMSettingItem alloc] initWithTitle:@"当前版本号" subTitle:TKIMAppVersion];
    TKIMSettingGroup *group4 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:version, nil];

    [groups addObject:group1];
    [groups addObject:group3];
    [groups addObject:group4];
    [groups addObject:group2];
    
    return groups;
}


/**
 *  @Author lpm, 15-10-29 11:10:06
 *
 *  @brief  获得设置列表分组
 *
 *  @return
 */
+ (NSMutableArray *) getNotifySetGroups
{
    NSMutableArray *groups = [NSMutableArray array];
    BOOL isAllowPush = [[TKIMNotificationCenter shareInstance] isAllowedNotification];
    NSString *str = isAllowPush?@"已开启":@"未开启";
    
    TKIMSettingItem *isOpen = [[TKIMSettingItem alloc] initWithTitle:@"新消息通知" subTitle:str];
    TKIMSettingGroup *group1 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:@"请在iphone的“设置”-“通知”中进行修改"
                                                                settingItems:isOpen, nil];
    
    TKIMSettingItem *sound = [[TKIMSettingItem alloc] initWithTitle:@"声音"  type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *showDetail = [[TKIMSettingItem alloc] initWithTitle:@"通知显示消息内容"  type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *harass = [[TKIMSettingItem alloc] initWithTitle:@"夜间防骚扰模式"  type:TKIMSettingItemTypeSwitch];

    TKIMSettingGroup *group2 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:@"开启“夜间防骚扰模式，将自动屏蔽23:00-8:00间的任何提醒”" settingItems:sound,showDetail, harass,nil];
    
    
    [groups addObject:group1];
    
    if (isAllowPush)
    {
        [groups addObject:group2];
    }
    
//#warning 以下三组为新增的
    TKIMSettingItem *earpieceMode = [[TKIMSettingItem alloc] initWithTitle:@"听筒模式" type:TKIMSettingItemTypeSwitch];
    TKIMSettingGroup *group5 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:earpieceMode, nil];

    TKIMSettingItem *cleanCache = [[TKIMSettingItem alloc] initWithTitle:@"清理缓存" ];
    TKIMSettingGroup *group3 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:cleanCache, nil];
    
    TKIMSettingItem *logOut = [[TKIMSettingItem alloc] initWithTitle:@"退出登录" type:TKIMSettingItemTypeMidTitle];
    TKIMSettingGroup *group4 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:logOut, nil];

    [groups addObject:group5];
    [groups addObject:group3];
    [groups addObject:group4];
    
    return groups;
}


/**
 *  @Author lpm, 15-10-29 11:10:33
 *
 *  @brief  格式化好友列表
 *
 *  @param array
 *
 *  @return
 */
+ (NSMutableArray *) getFriendListDataBy:(NSMutableArray *)array
{
    NSMutableArray *ans = [NSMutableArray array];
    
    // 按字母排序
    NSArray *serializeArray = [(NSArray *)array sortedArrayUsingComparator:^NSComparisonResult(TKIMUser *obj1, TKIMUser * obj2)
    {
        @try
        {
            int i;
        
            NSString *p1 = [obj1.pinYin uppercaseString];
            NSString *p2 = [obj1.pinYin uppercaseString];
            NSString *strA = p1;
            NSString *strB = p2;
            for (i = 0; i < strA.length && i < strB.length; i ++)
            {
                char a = [strA characterAtIndex:i];
                char b = [strB characterAtIndex:i];
                if (a > b)
                {
                    return (NSComparisonResult)NSOrderedDescending;//上升
                }
                else if (a < b)
                {
                    return (NSComparisonResult)NSOrderedAscending;//下降
                }
            }
            
            if (strA.length > strB.length)
            {
                return (NSComparisonResult)NSOrderedDescending;
            }
            else if (strA.length < strB.length)
            {
                return (NSComparisonResult)NSOrderedAscending;
            }
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@",exception.description);
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    char lastC = '1';
    NSMutableArray *data;
    NSMutableArray *oth = [NSMutableArray array];
    
    //将名字第一个字相同的分成一组
    for (TKIMUser *user in serializeArray)
    {
        @try
        {
            NSString *pinyin = [user.pinYin uppercaseString];
            pinyin = pinyin.length?pinyin:@"#";
            char c = [pinyin characterAtIndex:0];
            //判断是否为英文
            if (!isalpha(c))
            {
                [oth addObject:user];
            }
            else if (c != lastC)
            {
                lastC = c;
                if (data && data.count > 0)
                {
                    [ans addObject:data];
                }
                data = [NSMutableArray array];
                [data addObject:user];
            }
            else
            {
                [data addObject:user];
            }
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@",exception.description);
        }
    }
    
    if (data && data.count > 0)
    {
        [ans addObject:data];
    }
    
    if (oth.count > 0)
    {
        [ans addObject:oth];
    }
    return ans;
}


/**
 *  @Author lpm, 15-10-29 11:10:48
 *
 *  @brief  获得通讯录索引
 *
 *  @param array
 *
 *  @return
 */
+ (NSMutableArray *)getFriendListSectionBy:(NSMutableArray *)array
{
    NSMutableArray *section = [NSMutableArray array];
    [section addObject:UITableViewIndexSearch];
    for (NSArray *item in array) {
        TKIMUser *user = [item objectAtIndex:0];
        NSString *pinyin = [user.pinYin uppercaseString];
        pinyin = pinyin.length?pinyin:@"#";
        char c = [pinyin characterAtIndex:0];
        if (!isalpha(c)) {
            c = '#';
        }
        [section addObject:[NSString stringWithFormat:@"%c", toupper(c)]];
    }
    
    return section;
}


/**
 *  @Author lpm, 15-08-03 18:08:32
 *
 *  @brief  过滤消息
 *
 *  @param text
 *
 *  @return
 */
+(NSString *)filterMessage:(NSString *)text
{
    NSString *mstr =text;
    NSString *emotionPlist = TKIMSrcName(@"TKIMToolBar.plist");
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:emotionPlist];
    if (dic)
    {
        NSDictionary *data = dic[@"emotion"];
        if (data)
        {
            NSArray *keys = data[@"keys"];
            NSArray *values = data[@"values"];
            for (NSString *search in values)
            {
                NSString *searchStr = [NSString stringWithFormat:@"[@emoji_%@]",search];
                NSInteger index = [values indexOfObject:search];
                NSString *replace = [NSString stringWithFormat:@"%@",keys[index]];
                mstr = [mstr stringByReplacingOccurrencesOfString:searchStr withString:replace];
            }
        }
    }
    return mstr;
}



/**
 *  获取群组列表
 *
 *  @return
 */
+ (TKIMSettingGroup *) getGroupListItemsGroup
{
    TKIMSettingItem *newGroup = [[TKIMSettingItem alloc] initWithTitle:@"新建群聊" cssClass:@".IMIconCreateGroup"];
    TKIMSettingItem *addPublicRoom = [[TKIMSettingItem alloc] initWithTitle:@"添加公开群" cssClass:@".IMIconGroup"];
    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:newGroup,addPublicRoom, nil];
    return group;
}


/**
 *  获取群组设置列表
 *
 *  @return
 */
+ (TKIMSettingGroup *) getGroupSettingItems
{
    TKIMSettingItem *item1 = [[TKIMSettingItem alloc] initWithTitle:@"屏蔽群消息" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *item2 = [[TKIMSettingItem alloc] initWithTitle:@"接受并提示群消息" type:TKIMSettingItemTypeSwitch];
    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:item1,item2,nil];
    return group;
}


/**
 *  获取公众号设置列表
 *
 *  @return
 */
+(TKIMSettingGroup *)getOfficialSettingItems
{
    TKIMSettingItem *item1 = [[TKIMSettingItem alloc] initWithTitle:@"接收消息" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *item2 = [[TKIMSettingItem alloc] initWithTitle:@"消息置顶" type:TKIMSettingItemTypeSwitch];
    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:item1,item2,nil];
    return group;
}


/**
 *  @Author zhoufz, 16-4-7 16:10:06
 *
 *  @brief  获得帐号安全列表
 *
 *  @return
 */
+ (TKIMSettingGroup *) getAccountSafetyItems
{
    TKIMSettingItem *item1 = [[TKIMSettingItem alloc] initWithTitle:@"修改密码"];
    TKIMSettingItem *item2 = [[TKIMSettingItem alloc] initWithTitle:@"更换手机号码"];
    TKIMSettingGroup *group = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:item1,item2,nil];
    return group;
}


/**
 *  @Author zhoufz, 16-4-8 16:18:06
 *
 *  @brief  获得新的设置列表分组（更新至16-4-8）
 *
 *  @return
 */
+ (NSMutableArray *) getSettingGroups
{
    NSMutableArray *groups = [NSMutableArray array];
    TKIMSettingItem *msgWithoutInterruption = [[TKIMSettingItem alloc] initWithTitle:@"消息免打扰" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *chatToTop = [[TKIMSettingItem alloc] initWithTitle:@"置顶聊天" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *saveToAddbook = [[TKIMSettingItem alloc] initWithTitle:@"保持到通讯录" type:TKIMSettingItemTypeSwitch];
   
    TKIMSettingGroup *group1 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:msgWithoutInterruption, chatToTop,saveToAddbook, nil];
    
    TKIMSettingItem *cleanCache = [[TKIMSettingItem alloc] initWithTitle:@"清理缓冲" ];
    TKIMSettingGroup *group2 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:cleanCache, nil];
    
    TKIMSettingItem *logOut = [[TKIMSettingItem alloc] initWithTitle:@"退出登录" type:TKIMSettingItemTypeMidTitle];
    TKIMSettingGroup *group3 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:logOut, nil];
    
    [groups addObject:group1];
    [groups addObject:group2];
    [groups addObject:group3];
    
    return groups;
}


/**
 *  @Author zhoufz, 16-4-12 10:36:06
 
 *
 *  @brief
 *
 *  @return
 */
+ (NSMutableArray *) getChatDetailItems
{
    NSMutableArray *groups = [NSMutableArray array];
    TKIMSettingItem *msgWithoutInterruption = [[TKIMSettingItem alloc] initWithTitle:@"消息免打扰" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *chatToTop = [[TKIMSettingItem alloc] initWithTitle:@"置顶聊天" type:TKIMSettingItemTypeSwitch];
    TKIMSettingGroup *group1 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:msgWithoutInterruption, chatToTop, nil];
    
    TKIMSettingItem *cleanHisMsg = [[TKIMSettingItem alloc] initWithTitle:@"清空聊天记录" ];
    TKIMSettingGroup *group2 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:cleanHisMsg, nil];
    
    [groups addObject:group1];
    [groups addObject:group2];
    
    return groups;
}


/**
 *  @Author zhoufz, 16-4-12 14:36:06
 
 *
 *  @brief
 *
 *  @return
 */
+ (NSMutableArray *) getChatInformationItems
{
    NSMutableArray *groups = [NSMutableArray array];
    TKIMSettingItem *groupChatName = [[TKIMSettingItem alloc] initWithTitle:@"群聊名称" subTitle:@"设计一部"];
    TKIMSettingItem *groupAd = [[TKIMSettingItem alloc] initWithTitle:@"群简介"];
    TKIMSettingGroup *group1 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:groupChatName, groupAd, nil];

    
    TKIMSettingItem *msgWithoutInterruption = [[TKIMSettingItem alloc] initWithTitle:@"消息免打扰" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *chatToTop = [[TKIMSettingItem alloc] initWithTitle:@"置顶聊天" type:TKIMSettingItemTypeSwitch];
    TKIMSettingItem *saveToAdd = [[TKIMSettingItem alloc] initWithTitle:@"保存到通讯录" type:TKIMSettingItemTypeSwitch];
    TKIMSettingGroup *group2 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:msgWithoutInterruption, chatToTop, saveToAdd, nil];
    
    TKIMSettingItem *cleanHisMsg = [[TKIMSettingItem alloc] initWithTitle:@"清空聊天记录" ];
    TKIMSettingGroup *group3 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:cleanHisMsg, nil];
    
    TKIMSettingItem *delete = [[TKIMSettingItem alloc] initWithTitle:@"删除并退出" type:TKIMSettingItemTypeMidTitle ];
    TKIMSettingGroup *group4 = [[TKIMSettingGroup alloc] initWithHeaderTitle:nil footerTitle:nil settingItems:delete, nil];
    
    [groups addObject:group1];
    [groups addObject:group2];
    [groups addObject:group3];
    [groups addObject:group4];
    
    return groups;
}


/**
 *  @Author lpm, 15-10-29 11:10:33
 *
 *  @brief  格式化好友列表
 *
 *  @param array
 *
 *  @return
 */
+(NSMutableArray *) convertFriendListDataBy:(NSMutableArray *)array
{
    // 按字母排序
//    NSArray *serializeArray = [(NSArray *)array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
//       @try
//       {
//           int i;
//           NSString *p1 = [((TKIMUser *)obj1).pinYin uppercaseString];
//           NSString *p2 = [((TKIMUser *)obj2).pinYin uppercaseString];
//           NSString *strA = p1;
//           NSString *strB = p2;
//           for (i = 0; i < strA.length && i < strB.length; i ++)
//           {
//               char a = [strA characterAtIndex:i];
//               char b = [strB characterAtIndex:i];
//               if (a > b) {
//                   return (NSComparisonResult)NSOrderedDescending;//上升
//               } else if (a < b) {
//                   return (NSComparisonResult)NSOrderedAscending;//下降
//               }
//           }
//
//           if (strA.length > strB.length) {
//               return (NSComparisonResult)NSOrderedDescending;
//           } else if (strA.length < strB.length) {
//               return (NSComparisonResult)NSOrderedAscending;
//           }
//       }
//       @catch (NSException *exception) {
//           NSLog(@"%@",exception.description);
//       }
//       return (NSComparisonResult)NSOrderedSame;
//   }];
//
//
//    NSMutableArray *ans = [NSMutableArray array];
//    char lastC = '1';
//    NSMutableArray *data;
//    NSMutableArray *oth = [NSMutableArray array];
//
//    TKIMTableGroup *g5 = [[TKIMTableGroup alloc] init];
//    g5.groupId = @"#";
//    g5.groupInfo = @"#";
//    g5.styleClass = @"TKIMContactsSectionStyle3";
//    g5.items = oth;
//    g5.isExpand = YES;
//
//    //将名字第一个字相同的分成一组
//    for (TKIMUser *user in serializeArray)
//    {
//        @try
//        {
//            NSString *pinyin = [user.pinYin uppercaseString];
//            pinyin = pinyin.length?pinyin:@"#";
//            //取拼音第一个字
//            char c = [pinyin characterAtIndex:0];
//            //判断是否为英文
//            if (!isalpha(c))
//            {
//                [oth addObject:user];
//            }
//            else if (c != lastC)
//            {
//                if (data && data.count > 0)
//                {
//                    TKIMTableGroup *pinYin = [[TKIMTableGroup alloc] init];
//                    pinYin.groupId =    [NSString stringWithFormat:@"%c",lastC];
//                    pinYin.groupInfo = pinYin.groupId;
//                    pinYin.isExpand = YES;
//                    pinYin.styleClass = @"TKIMContactsSectionStyle3";
//                    pinYin.items = data;
//                    [ans addObject:pinYin];
//                }
//                lastC = c;
//                data = [NSMutableArray array];
//                [data addObject:user];
//            }
//            else
//            {
//                [data addObject:user];
//            }
//        }
//        @catch (NSException *exception)
//        {
//            NSLog(@"%@",exception.description);
//        }
//    }
//
//    if (data && data.count > 0)
//    {
//        TKIMTableGroup *pinYin = [[TKIMTableGroup alloc] init];
//        pinYin.groupId =    [NSString stringWithFormat:@"%c",lastC];
//        pinYin.groupInfo = pinYin.groupId;
//        pinYin.isExpand = YES;
//        pinYin.styleClass = @"TKIMContactsSectionStyle3";
//        pinYin.items = data;
//        [ans addObject:pinYin];
//    }
//
//    if (oth.count > 0)
//    {
//        [ans addObject:g5];
//    }
//    return ans;
    return [[NSMutableArray alloc] init];
}


/**
 *  @Author lpm, 16-04-26 10:04:06
 *
 *  @brief  获得外网ip
 *
 *  @param callBack
 */
+(void)getIpAddress:(void(^)(NSString *ip))callBack
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *ip = @"";
        @try
        {
            //var returnCitySN = {"cip": "218.17.161.51", "cid": "440300", "cname": "广东省深圳市"};
            NSError *error;
            NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
            NSString *content = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
            NSRange range1 = [content rangeOfString:@"{"];
            NSRange range2 = [content rangeOfString:@"}"];
            NSString *jsonStr = [content substringWithRange:NSMakeRange(range1.location, range2.location-range1.location+1)];
            NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
            ip = obj[@"cip"];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@",exception.description);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            callBack(ip);
        });
    });
}


/**
 *  @Author lpm, 16-04-26 10:04:06
 *
 *  @brief  获得所在地
 *
 *  @param callBack
 */
+(void)getAddress:(void(^)(NSString *addrees))callBack
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *cname = @"";
        @try
        {
            //var returnCitySN = {"cip": "218.17.161.51", "cid": "440300", "cname": "广东省深圳市"};
            NSError *error;
            NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
            NSString *content = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
            NSRange range1 = [content rangeOfString:@"{"];
            NSRange range2 = [content rangeOfString:@"}"];
            NSString *jsonStr = [content substringWithRange:NSMakeRange(range1.location, range2.location-range1.location+1)];
            NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
            cname = obj[@"cname"];
        }
        @catch (NSException *exception)
        {
            NSLog(@"%@",exception.description);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            callBack(cname);
        });
    });
}


/**
 *  @Author lpm, 16-05-06 14:05:46
 *
 *  @brief  验证相册权限
 *
 *  @return
 */
+(BOOL)AVAuthorizationStatus
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == kCLAuthorizationStatusRestricted || author ==kCLAuthorizationStatusDenied||![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        //无权限
        
        if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0"] != NSOrderedAscending)
        {
            UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要启用您的相机\n请启用相机-设置/隐私/相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        }
        else
        {
            UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要启用您的相机\n请启用相机-设置/隐私/相机" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
            [alert show];
        }
        return NO;
    }
    
    
    return YES;
}



/**
 *  @author zhengrs, 16-03-14 17:03:33
 *
 *  @brief 展示用户要显示的名字
 *
 *  @param user
 *
 *  @return
 */
+(NSString *)getShowNameWithUser:(TKIMUser *)user
{
    NSString *senderName;
    if (![TKIMStringHelper isEmpty:user.remark])
    {
        senderName = user.remark;
    }
    if ([TKIMStringHelper isEmpty:senderName])
    {
        senderName = user.nickName;
    }
    if ([TKIMStringHelper isEmpty:senderName])
    {
        senderName = user.userName;
    }
    if ([TKIMStringHelper isEmpty:senderName])
    {
        senderName = user.userID;
    }
    return senderName;
}


/**
 *  @Author lpm, 16-04-12 12:04:13
 *
 *  @brief  转换电话号码
 *
 *  @param mobile
 *
 *  @return
 */
+(NSString *)formatMoblie:(NSString *)mobile
{
    NSMutableString *result = [NSMutableString string];
    NSInteger count = mobile.length-1;
    for (NSInteger i=count; i>=0; i--)
    {
        char c = [mobile characterAtIndex:i];
        [result insertString:[NSString stringWithFormat:@"%c",c] atIndex:0];
        if ((i+1)%4==0)
        {
            [result insertString:@" " atIndex:0];
        }
    }
    return result;
}



/**
 *  @Author lpm, 16-05-24 09:05:43
 *
 *  @brief  格式头像显示的名称
 *
 *  @param name
 *
 *  @return
 */
+(NSString *)formatHeadName:(NSString *)name
{
    NSString *result = @"";
    if (name.length && name.length>2){
        result = [name substringFromIndex:1];
    }else{
        result = name;
    }
    return result;
}


/**
 *  @Author lpm, 16-05-25 09:05:52
 *
 *  @brief  展示大图
 */
+(void)showUserBigImage:(TKIMUser *)user fromView:(UIImageView *)fromView inView:(UIView *)inview;
{
    TKIMImageBrowserView * browseView = [[TKIMImageBrowserView alloc] initWithFrame:inview.bounds contentView:inview];
    browseView.orgImagUrl = user.originalPhotoUrl;;
    browseView.thubImageUrl = user.thumbPhotoUrl;
    if (user.originalPhotoUrl){
        browseView.orgImagUrl = user.originalPhotoUrl;
    }else if(user.thumbPhotoUrl){
        browseView.orgImagUrl  = user.thumbPhotoUrl;
    }
    [browseView show:fromView];
}

/**
 *  @Author lpm, 15-12-04 14:12:23
 *
 *  @brief  过滤文字消息
 *
 *  @param text
 *
 *  @return
 */
+(NSAttributedString *)filterTxtMessage:(NSString *)text
{
    return [self filterTxtMessage:text font:15 imageBounds:CGRectMake(0, -6, 23,23) isDetectLinks:YES];
}


/**
 *  @Author lpm, 15-12-04 14:12:23
 *
 *  @brief  过滤文字消息
 *
 *  @param text
 *
 *  @return
 */
+(NSAttributedString *)filterTxtMessage:(NSString *)text font:(CGFloat)f imageBounds:(CGRect)bounds isDetectLinks:(BOOL)isDetectLinks
{
    if (!text || ![text isKindOfClass:[NSString class]]){
        return nil;
    }
    NSString *emotionPlist = TKIMSrcName(@"TKIMEmotion.json");
    NSData *data = [NSData dataWithContentsOfFile:emotionPlist];
    NSDictionary *dic = (NSDictionary *)[TKIMDataHelper dataToObject:data];
    NSDictionary *emotion = dic[@"emotion"];
    
    NSMutableArray *textArray = [NSMutableArray array];
    NSMutableArray *imgArray = [NSMutableArray array];
    
    NSRange range = [text rangeOfString:@"["];
    if (range.location != NSNotFound){
        NSDictionary *userInfo =  [TKIMStringHelper replaceString:text from:@"\\[@emoji_\\d+\\.(gif|png)\\]" to:@"┠┨" ];
        NSString *textCopy = userInfo[@"replaceString"];
        textArray = (NSMutableArray *)[textCopy componentsSeparatedByString:@"┠┨"];
        NSArray *ts =  userInfo[@"matchResults"];
        if (emotion){
            //遍历消息文字数组
            for (NSString *value in ts){
                NSString *imageName = emotion[value];
                if (imageName){
                    [imgArray addObject:imageName];
                }
            }
        }
    }
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
    
    if (imgArray && imgArray.count == 0){
        NSAttributedString *substr =[[NSAttributedString alloc] initWithString:text];
        [attributedText appendAttributedString:substr];
    }else{
        for (NSUInteger i = 0; i < textArray.count; i++){
            NSAttributedString *substr =[[NSAttributedString alloc] initWithString:[textArray objectAtIndex:i]];
            [attributedText appendAttributedString:substr];
            if (i != textArray.count - 1){
                NSTextAttachment *attch = [[NSTextAttachment alloc] init];
                NSInteger count = imgArray.count -1;
                if(count < i){
                    continue;
                }
                
                NSString *url =  [NSString stringWithFormat:@"%@",imgArray[i]];
                NSString *imgUrl = TKIMSrcName(url);
                NSString *str = [[[imgUrl componentsSeparatedByString:@"/"] lastObject] componentsSeparatedByString:@"."][0];
                NSString *x = [NSString stringWithFormat:@"%@",str];
//                UIImage *image = [UIImage sd_animatedGIFNamed:x];
                NSData *gifData = [NSData dataWithContentsOfFile:imgUrl];
                UIImage *image = [UIImage sd_imageWithGIFData:gifData];
                attch.bounds = bounds;
                attch.image = image;
                [attch.image  setAccessibilityIdentifier:url];
                NSAttributedString *substr2 = [NSAttributedString attributedStringWithAttachment:attch];
                [attributedText appendAttributedString:substr2];
            }
        }
    }
    
    if (isDetectLinks) {
        //给文字中的链接做标记
        //        [TKIMAttributedLabelURL detectLinks:attributedText];
    }
    
    // 一定要设置字体,保证计算出来的尺寸是正确的
    UIFont *font = [UIFont systemFontOfSize:f];
    [attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
    return attributedText;
}



@end
